package com.xm.uti;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库工具类
 * 
 * @author
 *
 */
public class DBManager {
  private final static String DRIVER = "com.mysql.jdbc.Driver";
  private final static String URL = "jdbc:mysql://localhost:3306/furniture-four?useSSL=false&characterEncoding=utf-8";
  private final static String USER = "root";
  private final static String PWD = "admin";

  public static void main(String[] args) {
    System.out.println(getConnection());
  }

  public static Connection getConnection() {
    try {
      Class.forName(DRIVER);
      return DriverManager.getConnection(URL, USER, PWD);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 执行增删改的方法
   * 
   * @param sql
   * @return
   */
  public static int executeUpdate(String sql) {
    System.out.println("执行的sql语句是" + sql);
    Connection conn = null;
    Statement st = null;
    try {
      conn = getConnection();
      st = conn.createStatement();
      return st.executeUpdate(sql);
    } catch (SQLException e) {
      e.printStackTrace();
      return 0;
    } finally {
      closeAll(conn, st, null);
    }

  }

  /**
   * 执行查询的方法
   * 
   * @param sql
   * @return
   */
  public static QueryDataResult executeQuery(String sql) {
    System.out.println("执行的sql语句是" + sql);
    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      st = conn.createStatement();
      rs = st.executeQuery(sql);
      return new QueryDataResult(conn, st, rs);
    } catch (SQLException e) {
      e.printStackTrace();
      closeAll(conn, st, rs);
      return null;
    }
  }

  /**
   * 关闭方法
   * 
   * @param conn
   * @param st
   * @param rs
   */
  public static void closeAll(Connection conn, Statement st, ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
      if (st != null) {
        st.close();
      }
      if (conn != null) {
        conn.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}